<template>
  <div>
    <div class="myRobot myRobotChat">
      <robotNav></robotNav>
      <div class="myRobotRight">
        <div class="myRobotChatTop">
          <div v-for="(item, index) in chatList">
            <div class="chat_list user">
              <div class="chat_list_left">
                <div class="list_left_txt">
                  <div class="left_txt_question">
                    <div class="txt_question_dd">{{ item.create_time }}</div>
                    <div class="txt_question_p">{{ item.user_questions }}</div>
                  </div>
                </div>
              </div>
              <div class="chat_list_right"><img :src="img_dog"/></div>
            </div>
            <div class="chat_list dog">
              <div class="chat_list_left">
                <div class="list_left_txt">
                  <div class="left_txt_question">
                    <div class="txt_question_dt">{{ item.answer_time }}</div>
                    <div class="txt_question_con">
                      <markdown-it-vue-light class="txt_question_p" :content="item.machine_answer"/>
                      <div class="txt_question_icon">
                        <div class="question_icon_li notBlue " :class="{'active': item.is_positive_reviews == 1}" @click="like(item)">
                          <img src="@a/img/sv68on.svg"/>
                          <img src="@a/img/sv68.svg"/>
                        </div>
                        <div class="question_icon_li notBlue" :class="{'active': item.is_positive_reviews == -1}" @click="unlike(item)">
                          <img src="@a/img/sv69on.svg"/>
                          <img src="@a/img/sv69.svg"/>
                        </div>
                      </div>
                    </div>
                    <div class="txt_question_source" @click="toggleClass(item)" :class="{ 'active': item.isActive }" v-if="item.referenced_files.length">
                      <div class="question_source_title notBlue">查看来源<i class="el-icon-arrow-down"></i></div>
                      <div class="question_source_down">
                        <a :href="url.url" class="source_down_list" v-for="(url, url_index) in item.referenced_files"
                           target="_blank">{{ url.url }}_{{ url.score }}</a>
                      </div>
                    </div>
                    <el-form ref="form" label-width="50px" v-if="item.event_details.id && item.is_answer_over" style="border: 1px solid  rgb(217, 236, 255);padding: 20px;">
                      <el-tag >{{item.event_details.form_name}}</el-tag>
                      <el-form-item :label="field" v-for="(field, index) in item.event_details.form_field" :key="'field_'+index">
                        <el-input v-model="item.user_submission[field]" name="field" :readonly="item.is_event_submission==1"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" v-if="!item.is_event_submission" @click="submitUserInfo(item)">提交信息</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
              <div class="chat_list_right"><img :src="img_ai"/></div>
            </div>
          </div>
        </div>
        <div class="myRobotChat_submit">
          <div class="chatDogHome_submit_input">
            <div class="submit_input_left">
              <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 5}"
                  :placeholder="prompt_placeholder"
                  v-model="input"
                  v-enter-prevent="send">
              </el-input>
            </div>
            <div class="submit_input_btn">
              <div class="input_btn_click" @click="send" v-if="!showLoading"><img src="@a/img/bn29.png"/></div>
              <div class="la-ball-fall la-2x input_btn_loading" :class="{ 'is-active': showLoading }">
                <div></div>
                <div></div>
                <div></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import {MessageBox, Message} from 'element-ui';
import robotNav from "@c/common/robotNav/robotNav";
import {Loading} from 'element-ui';

import MarkdownItVueLight from 'markdown-it-vue/dist/markdown-it-vue-light.umd.min.js'
import 'markdown-it-vue/dist/markdown-it-vue-light.css'
import {api} from "@/api-js";


export default {
  name: "chatDog",
  data() {
    return {
      prompt_placeholder: '你们公司的企业文化是什么。(Shift + Enter = 换行)',
      showLoading: false,
      img_ai: require("@a/img/bg30.jpg"),
      img_dog: this.baseURL + this.$store.getters.memberInfo.avatar,
      chatList: [],
      input: '',
      conversation_id: 0,
      user_submission: {},
    };
  },

  components: {
    robotNav,
    MarkdownItVueLight
  },
  directives: {
    'enter-prevent': {
      inserted: function (el, binding) {
        el.addEventListener('keydown', function (event) {
          if (event.keyCode === 13 && !event.shiftKey) {
            event.preventDefault();
            event.stopPropagation();
            // 执行绑定的函数
            binding.value();
          }
        });
      }
    }
  },
  methods: {
    async like(item) {
      const [e, r] = await api.chat.like(item.id);
      if(!e && r ){
        if(r.code){
          item.is_positive_reviews = 1;
        }
      }
    },
    async unlike(item) {
      const [e, r] = await api.chat.unlike(item.id);
      if(!e &&r ){
        if(r.code) {
          item.is_positive_reviews = -1;
        }
      }
    },
    async submitUserInfo(item){
      const [e, r] = await api.chat.userSubmitEvent({
        msg_id: item.id,
        user_submission: item.user_submission
      });
      if(!e && r ){
        if(r.code) {
          item.is_event_submission = 1;
          Message({
            message: '提交成功',
            type: 'success'
          });
        }
      }
    },

    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDateTime;
    },
    toggleClass(item) {
      item.isActive = !item.isActive;
    },
    async send() {
      let that = this;
      this.showLoading = true;
      let msg = that.input;
      that.input = '';

      if (this.conversation_id === 0) {
        const [chat_e, chat_r] = await api.chat.createConversation({
          robot_id: this.$store.getters.robotId,
          query: msg,
        });
        if (!chat_e && chat_r) {
          this.conversation_id = chat_r.result.id;
        } else {
          return;
        }
      }

      const [msg_e, msg_r] = await api.chat.createMessage({
        conversation_id: this.conversation_id,
        user_questions: msg,
        robot_id: this.$store.getters.robotId,
      });

      let msg_id = 0;
      if (!msg_e && msg_r) {
        if(!msg_r.code){
          that.showLoading = false;
          return;
        }
        msg_id = msg_r.result.id;
        this.chatList.push({
          create_time: this.getCurrentDateTime(),
          answer_time: this.getCurrentDateTime(),
          user_questions: msg,
          machine_answer: '',
          referenced_files: [],
          isActive: false,
          id: msg_r.result.id,
          is_positive_reviews: 0,
          user_submission: {},
          event_details: {},
          is_event_submission: 0,
          is_answer_over: 0,
        })
      } else {
        that.showLoading = false;
        return;
      }


      let source = new EventSource(that.baseURL + `/api1/chat/chat?event_name=newChatMsg&msg=${msg}&robot_id=`
          + this.$store.getters.robotId + '&msg_id=' + msg_id);


      //监听test事件
      source.addEventListener('newChatMsg', function (event) {
        if (event.data) {
          if (event.data === 'end') {
            that.showLoading = false;
            let len = that.chatList.length;
            that.chatList[len - 1].is_answer_over = 1;
            source.close()
          } else {
            let res = event.data
            res = JSON.parse(res)
            res = res.title

            let len = that.chatList.length;
            that.chatList[len - 1].machine_answer += res;
            that.chatList = JSON.parse(JSON.stringify(that.chatList))

          }
        }
        window.scrollTo(0, document.body.scrollHeight);
      });

      const [e, r] = await api.robotFiles.reference(this.$store.getters.robotId, msg, msg_id)
      if (!e && r) {
        let len = that.chatList.length;
        that.chatList[len - 1].referenced_files = r.result.references
        if(r.result.event){
          that.chatList[len - 1].event_details = r.result.event
          for(let i in r.result.event.form_field){
            let field = r.result.event.form_field[i];
            this.chatList[len - 1].user_submission[field] = ''
          }

        }
      }
    }
  },
}
</script>


<style>
@import "myRobotChat.css";
</style>